package com.yyfax.ph.common.imageselector.activity;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.*;
import butterknife.BindView;
import butterknife.OnClick;
import com.bumptech.glide.Glide;
import com.yyfax.common.CLog;
import com.yyfax.common.tools.SystemTool;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.ph.R;
import com.yyfax.ph.base.PermissionActivity;
import com.yyfax.ph.common.GlobalVariableConfig;
import com.yyfax.ph.common.imageselector.adapter.FolderAdapter;
import com.yyfax.ph.common.imageselector.adapter.ImageGridAdapter;
import com.yyfax.ph.common.imageselector.bean.Image;
import com.yyfax.ph.common.imageselector.utils.SerializableMap;
import com.yyfax.ph.common.utils.BitmapOptimizer;
import com.yyfax.ph.common.utils.Constants;
import com.yyfax.ph.common.imageselector.bean.Folder;
import com.yyfax.ph.common.imageselector.bean.ImageBean;
import com.yyfax.ph.common.imageselector.utils.FileUtils;
import com.yyfax.ph.common.imageselector.utils.TimeUtils;
import com.yyfax.ph.home.imageupload.ImageSelectArguments;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * multiple photo selector
 */
public class PhotoSelectorActivity extends PermissionActivity {
	private static final String TAG = PhotoSelectorActivity.class.getSimpleName();

	public static final String EXTRA_ORIGINAL_PHOTO_PATHS = "original_photo_paths";
	public static final String EXTRA_COMPRESSED_BEANS = "compressed_beans";

	private static final int LOADER_ALL = 10;
	private static final int LOADER_CATEGORY = 11;

	public static final String SELECT_ARGUMENTS = "select_arguments";
	public static final String BUNDLE_ARGUMENTS = "bundle_arguments";

	/**
	 * 默认选择集
	 */
	public static final String EXTRA_DEFAULT_SELECTED_LIST = "default_selected_list";

	public static final int SELECT_MODE_SINGLE = 0;
	public static final int SELECT_MODE_MULTI = 1;

	private static final int MAX_SELECT_COUNT = 50;

	private static final long MIX_FILE_SIZE = 1024 * 200;

	private static final int COMPRESS_QUALITY = 90;

	private static final int DEFAULT_WIDTH = 1000;
	private static final int DEFAULT_HEIGHT = 1777;

	private static final String EXTRA_FORMAT_WIDTH = "target_format_width";
	private static final String EXTRA_FORMAT_HEIGHT = "target_format_height";

	private static final String KEY_SELECT_ARGUMENTS = "KEY_SELECT_ARGUMENTS";
	private static final String KEY_NEED_COMPRESS = "KEY_NEED_COMPRESS";
	private static final String KEY_COMPRESSED = "KEY_COMPRESSED";
	private static final String ARG_CURRENT_PHOTO_PATH = "current_photo_path";

	@BindView(R.id.category_btn)
	TextView mAlbumNameTv;//选择相册
	@BindView(R.id.count_tv)
	TextView mSelectedCountTv;
	@BindView(R.id.finish_tv)
	TextView mCompleteTv;
	@BindView(R.id.footer)
	RelativeLayout mFooter;
	@BindView(R.id.grid)
	GridView mGridView;//图片Grid
	@BindView(R.id.timeline_area)
	TextView mDateBarTv;//顶部日期条

	private ListPopupWindow mFolderPopup;
	private ImageGridAdapter mImageAdapter;
	private FolderAdapter mFolderPopupAdapter;
	/**
	 * 文件夹数据
	 */
	private ArrayList<Folder> mAlbumList = new ArrayList<>();
	/**
	 * 是否处于可选状态
	 */
	public boolean mSelectable = true;
	/**
	 * 存储到相册
	 */
	private String mCurrentPhotoPath;
	private boolean mHasFolder = false;

	private int mTargetWidth = DEFAULT_WIDTH;
	private int mTargetHeight = DEFAULT_HEIGHT;

	private int mSelectMode = SELECT_MODE_MULTI;
	private int mCurrentIndex = 0;

	private String mPhotoCacheDir = FileUtils.DEFAULT_SAVE_IMAGE_PATH_UPLOAD;

	private ArrayList<String> mNeedCompressImages = new ArrayList<>();//需要压缩的图片
	private Map<String, String> mCompressedImages = new HashMap<>();  //已经压缩的图片

	private Handler mCompressedHandler = new ImageHandler(this);

	private ImageSelectArguments mArguments;
	/**
	 * 当前查看的文件夹路径
	 */
	private String mFolderPath;
	private int mPermissionRequestCodeCamera = DEFAULT_PERMISSION_REQUEST_CODE_CAMERA_EXTERNAL_STORAGE;

	public static void startForResult(Activity activity, ImageSelectArguments arguments, int requestCode) {
		Intent intent = new Intent(activity, PhotoSelectorActivity.class);
		CLog.i(TAG, "选择图片参数-11->" + arguments.toString());
		Bundle bundle = new Bundle();
		bundle.putParcelable(SELECT_ARGUMENTS, arguments);
		intent.putExtra(BUNDLE_ARGUMENTS, bundle);
		activity.startActivityForResult(intent, requestCode);
	}

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {

	}

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		return null;
	}

	private static class ImageHandler extends Handler {
		WeakReference<PhotoSelectorActivity> weakReference;

		ImageHandler(PhotoSelectorActivity aty) {
			weakReference = new WeakReference<>(aty);
		}

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			PhotoSelectorActivity aty = weakReference.get();
			if (aty != null) {
				aty.processCompress(msg.obj);
			}
		}
	}

	private void processCompress(Object result) {
		CLog.i(TAG, "成功压缩图片mCurrentIndex=" + mCurrentIndex);
		@SuppressWarnings("unchecked")
		Map<String, String> compressed = (Map<String, String>) result;
		mCompressedImages.putAll(compressed);

		if ((mCurrentIndex + 1) == mNeedCompressImages.size()) {
			CLog.i(TAG, "压缩完成");
			completedCompress();
		} else {
			mCurrentIndex++;
			try {
				compress(mNeedCompressImages.get(mCurrentIndex));
			} catch (Exception e) {
				finish();
			}
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		CLog.i(TAG, "PhotoSelectorActivity onCreate()");
		if (savedInstanceState != null) {
			readBundle(savedInstanceState);
		}
		initGridView();
		mFolderPath = "";
		getSupportLoaderManager().initLoader(LOADER_ALL, null, mLoaderCallback);
	}

	private void initArguments() {
		if (null == getIntent()) finish();
		Bundle bundle = getIntent().getBundleExtra(BUNDLE_ARGUMENTS);
		mArguments = bundle.getParcelable(SELECT_ARGUMENTS);
		mSelectMode = mArguments.selectMode;
		CLog.i(TAG, "选择图片参数-22->" + mArguments.toString());
		ArrayList<ImageBean> imageBeans = mArguments.compressedImages;
		for (ImageBean bean : imageBeans) {
			mCompressedImages.put(bean.originalPath, bean.newPath);
		}
		if (mArguments.showCamera) {
			FileUtils.createTmpFile(this, mPhotoCacheDir);
		}
	}

	@Override
	protected void onStart() {
		super.onStart();
		CLog.i(TAG, "PhotoSelectorActivity onStart()");
		if (GlobalVariableConfig.isThirdPartyPageOpened()) {
			GlobalVariableConfig.setIgnoreGestureFlag(false);
			GlobalVariableConfig.setThirdPartyPageOpenedFlag(false);
		}
	}

	@Override
	protected void onStop() {
		Glide.get(this).clearMemory();
		super.onStop();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	public void onBackBtnPressed() {
		super.onBackBtnPressed();
		onBackPressed();
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		setResult(RESULT_CANCELED);
		finish();
	}

	@Override
	public void onRightBtnPressed() {
		super.onRightBtnPressed();
		PhotoViewActivity.startForResult(this, mArguments.selectedImages);
	}

	@Override
	public int getTopBarBackgroundColor() {
		return getColors(R.color.color_white);
	}

	@Override
	public void pretreatmentAfterSetBaseView() {
		initArguments();
	}

	private void initGridView() {
		mAlbumNameTv.setText(R.string.folder_all);

		if (mArguments.selectedImages.size() != 0) {
			mSelectedCountTv.setText(String.valueOf(mArguments.selectedImages.size()));
			mCompleteTv.setEnabled(true);
		} else {
			mSelectedCountTv.setText("0");
			mCompleteTv.setEnabled(false);
		}

		mGridView.setOnScrollListener(new AbsListView.OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView absListView, int state) {
				if (state == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {//停止滑动状态
					CLog.i(TAG, "上图片选择 停止滑动-");
					Glide.get(PhotoSelectorActivity.this).clearMemory();
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
				if (mDateBarTv.getVisibility() == View.VISIBLE) {
					int index = firstVisibleItem + 1 == view.getAdapter().getCount() ?
							view.getAdapter().getCount() - 1 : firstVisibleItem + 1;
					Image image = (Image) view.getAdapter().getItem(index);
					mDateBarTv.setText(TimeUtils.formatPhotoDate(image.path));
				}
			}
		});

		// 图片选择模式
		mImageAdapter = new ImageGridAdapter(this, mArguments.showCamera);
		mImageAdapter.setSingleSelect(mSelectMode == SELECT_MODE_SINGLE);
		mGridView.setAdapter(mImageAdapter);
		mGridView.getViewTreeObserver().addOnGlobalLayoutListener(
				new ViewTreeObserver.OnGlobalLayoutListener() {
					@Override
					@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
					public void onGlobalLayout() {
						final int width = (int) (mGridView.getWidth() + 2 * getResources().getDimension(R.dimen.dp_x10));
						final int height = mGridView.getHeight();
						createPopupFolderList(width, height);

						if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
							mGridView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
						} else {
							mGridView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
						}
					}
				}
		);
		mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
				if (!mSelectable) return;
				if (mImageAdapter.isShowCamera() && i == 0) {// 如果显示照相机，则第一个Grid显示为照相机，处理特殊逻辑
					if (mArguments.remainCount == mArguments.selectedImages.size()) {// 最大选择数量
						showToast(String.format(getString(R.string.msg_amount_limit), mArguments.maxCount + ""));
						return;
					}
					showCameraAction();
					return;

				}
				onClickPhotoItem(adapterView, i, mSelectMode);// 如果是普通选择
			}
		});
		mFolderPopupAdapter = new FolderAdapter(this);
		CLog.i(TAG, "PhotoSelectorActivity onViewCreated mCurrentPhotoPath=" + mCurrentPhotoPath);
	}

	@Override
	public int getContentViewRes() {
		return R.layout.mis_activity_main;
	}

	@Override
	public void initContentView() {
		setBtnBackVisible(true);
		setTitleVisible(true);
		setTitle(R.string.photo_album);
		setTitleLeftVisible(false);
		setBtnRightTx(R.string.preview);
		setBtnRightVisible(mArguments.selectedImages.size() > 0);
	}


	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		CLog.i(TAG, "PhotoSelectorActivity onActivityResult()");
		if (Activity.RESULT_OK == resultCode) {
			if (PhotoViewActivity.REQUEST_CODE == requestCode) {//预览返回(可能在预览界面中取消选择某些照片)
				ArrayList<String> paths = data.getStringArrayListExtra(PhotoViewActivity.RESULT_EXTRA_PHOTO_PATH);
				CLog.i(TAG, "onActivityResult updateViews paths=" + paths.toString());
				updateViews(paths);
				CLog.i(TAG, "onActivityResult updateViews mSelectedImages=" + mArguments.selectedImages.toString());
			} else if (PhotoSelectorActivity.REQUEST_CODE_CAMERA == requestCode) {
				CLog.i(TAG, "PhotoSelectorActivity onActivityResult mCurrentPhotoPath=" + mCurrentPhotoPath);
				if (!TextUtils.isEmpty(mCurrentPhotoPath)) {
					//showLoading(false);
					mArguments.selectedImages.add(mCurrentPhotoPath);
					onImageSelected(mCurrentPhotoPath);
					CLog.i(TAG, "PhotoSelectorActivity onActivityResult updateViews mCurrentPhotoPath=" + mCurrentPhotoPath);
					CLog.i(TAG, "PhotoSelectorActivity onActivityResult updateViews mSelectedImages=" + mArguments.selectedImages.toString());
					updateViews(mArguments.selectedImages);
					SystemTool.refreshGallery(this, mCurrentPhotoPath);
					mCurrentPhotoPath = null;
					mFolderPath = "";
					getSupportLoaderManager().restartLoader(LOADER_ALL, null, mLoaderCallback);
					mAlbumNameTv.setText(R.string.folder_all);
					mImageAdapter.setShowCamera(true);
				}
			}
		}
	}

	@OnClick({R.id.finish_tv, R.id.category_btn})
	public void onClick(View view) {
		super.onClick(view);
		switch (view.getId()) {
			case R.id.finish_tv:
				mSelectable = false;
				CLog.i(TAG, "选择的图片 PhotoSelectorActivity->" + mArguments.selectedImages.toString());
				startCompress();
				break;
			case R.id.category_btn:
				if (mFolderPopup.isShowing()) {
					mFolderPopup.dismiss();
				} else {
					mFolderPopup.show();
					int index = mFolderPopupAdapter.getSelectIndex();
					index = index == 0 ? index : index - 1;
					if (null != mFolderPopup.getListView())
						mFolderPopup.getListView().setSelection(index);
				}
				break;
		}
	}

	/**
	 * call by PhotoSelectorActivity and PhotoSelectorActivity
	 */
	@SuppressLint("SetTextI18n")
	public void updateViews(ArrayList<String> paths) {
		mArguments.selectedImages = paths;
		int selectedSize = paths != null ? paths.size() : 0;
		mImageAdapter.setDefaultSelected(paths);
		mCompleteTv.setEnabled(true);
		mSelectedCountTv.setText(String.valueOf(selectedSize));
	}

	public void onImageSelected(String path) {
		if (mSelectMode == SELECT_MODE_MULTI) {
			if (!mArguments.selectedImages.contains(path)) {
				mArguments.selectedImages.add(path);
			}
		} else if (mSelectMode == SELECT_MODE_SINGLE) {
			mArguments.selectedImages.clear();
			mArguments.selectedImages.add(path);
		}
		setBtnRightVisible(mArguments.selectedImages.size() > 0);
	}

	public void onImageUnselected(String path) {
		if (mArguments.selectedImages.contains(path)) {
			mArguments.selectedImages.remove(path);
		}
		setBtnRightVisible(mArguments.selectedImages.size() > 0);
	}

	/**
	 * 点击"完成"按钮回调
	 */
	public void startCompress() {
		setBtnBackEnable(false);
		CLog.i(TAG, "选择的图片->" + mArguments.selectedImages.toString());
		if (mArguments.selectedImages.size() > 0) {
			for (String path : mArguments.selectedImages) {
				if (!mCompressedImages.containsKey(path)) {//如果已经压缩的图片中没有这个图片，则添加到待压缩图片集合中
					mNeedCompressImages.add(path);
				}
			}
			CLog.i(TAG, mNeedCompressImages.size() + "张图片需要压缩");
			if (mNeedCompressImages.size() > 0) {
				mCurrentIndex = 0;
				showLoading(false);
				compress(mNeedCompressImages.get(0));
			} else {
				CLog.i(TAG, mCompressedImages.size() + "张图片已压缩");
				completedCompress();
			}
		} else {
			CLog.i(TAG, "没有需要压缩的图片");
			Intent data = new Intent();
			data.putStringArrayListExtra(EXTRA_ORIGINAL_PHOTO_PATHS, null);
			data.putParcelableArrayListExtra(EXTRA_COMPRESSED_BEANS, null);
			setResult(RESULT_OK, data);
			finish();
		}
	}

	private void compress(final String path) {
		if (TextUtils.isEmpty(path)) {
			return;
		}
		// 判断原来是否已压缩
		if (mCompressedImages.containsKey(path)) {//todo 多余 删掉
			return;
		}

		File target = new File(path);
		if (!target.exists()) {
			return;
		}
		//如果大于200K, 开始压缩
		GlobalVariableConfig.getExecutorService().execute(new Runnable() {
			@Override
			public void run() {
				Map<String, String> currentCompressPicturePath = new HashMap<>();
				String targetImageAbsolutePath = BitmapOptimizer.autoOptimize(PhotoSelectorActivity.this, path, mPhotoCacheDir);
				currentCompressPicturePath.put(path, targetImageAbsolutePath);

				Message message = mCompressedHandler.obtainMessage();
				message.obj = currentCompressPicturePath;
				mCompressedHandler.sendMessage(message);
			}
		});
	}

	/**
	 * 压缩流程结束，把压缩结果和原图路径集合作为Result Data返回
	 */
	private void completedCompress() {
		dismissLoading();
		ArrayList<ImageBean> compressedBeans = new ArrayList<>();
		ArrayList<String> originalPhotoPaths = new ArrayList<>();
		CLog.i(TAG, "mCompressedImages.size=" + mCompressedImages.size());
		for (String path : mArguments.selectedImages) {
			if (mCompressedImages.containsKey(path)) {                     //
				ImageBean bean = new ImageBean(path, mCompressedImages.get(path));//ImageBean(原图路径：压缩后的路径)
				compressedBeans.add(bean);
				originalPhotoPaths.add(mCompressedImages.get(path));//add:压缩后的路径
			} else {//todo 在什么情况下会走这一步? del
				originalPhotoPaths.add(path);           //add:原图路径
			}
		}
		CLog.i(TAG, "压缩数量=" + compressedBeans.size());
		Intent data = new Intent();
		data.putStringArrayListExtra(EXTRA_ORIGINAL_PHOTO_PATHS, originalPhotoPaths);
		data.putParcelableArrayListExtra(EXTRA_COMPRESSED_BEANS, compressedBeans);
		setResult(RESULT_OK, data);
		finish();
	}

	private void readBundle(Bundle savedInstanceState){
		if (savedInstanceState != null) {
			mArguments = savedInstanceState.getParcelable(KEY_SELECT_ARGUMENTS);
			mNeedCompressImages = savedInstanceState.getStringArrayList(KEY_NEED_COMPRESS);
			SerializableMap tempMap = (SerializableMap) savedInstanceState.get(KEY_COMPRESSED);
			mCompressedImages = tempMap.getMap();
			mCurrentPhotoPath = savedInstanceState.getString(ARG_CURRENT_PHOTO_PATH, "");
			CLog.i(TAG, "PhotoSelectorFragment on readBundle mCurrentPhotoPath=" + mCurrentPhotoPath);
			CLog.i(TAG, "PhotoSelectorActivity onRestoreInstanceState mArguments=" + mArguments.toString());
			CLog.i(TAG, "PhotoSelectorActivity onRestoreInstanceState mSelectedImages=" + mArguments.selectedImages.toString());
			CLog.i(TAG, "PhotoSelectorActivity onRestoreInstanceState mNeedCompressImages=" + mNeedCompressImages.toString());
			CLog.i(TAG, "PhotoSelectorActivity onRestoreInstanceState mCompressedImages=" + mCompressedImages.toString());
		}
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		CLog.i(TAG, "PhotoSelectorActivity onRestoreInstanceState");
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		SerializableMap tempMap = new SerializableMap();
		tempMap.setMap(mCompressedImages);
		outState.putParcelable(KEY_SELECT_ARGUMENTS, mArguments);
		outState.putStringArrayList(KEY_NEED_COMPRESS, mNeedCompressImages);
		outState.putSerializable(KEY_COMPRESSED, tempMap);
		CLog.i(TAG, "PhotoSelectorFragment onSaveInstanceState mCurrentPhotoPath=" + mCurrentPhotoPath);
		outState.putString(ARG_CURRENT_PHOTO_PATH, mCurrentPhotoPath);
		CLog.i(TAG, "PhotoSelectorActivity onSaveInstanceState mArguments=" + mArguments.toString());
		CLog.i(TAG, "PhotoSelectorActivity onSaveInstanceState mSelectedImages=" + mArguments.selectedImages.toString());
		CLog.i(TAG, "PhotoSelectorActivity onSaveInstanceState mNeedCompressImages=" + mNeedCompressImages.toString());
		CLog.i(TAG, "PhotoSelectorActivity onSaveInstanceState tempMap=" + tempMap.toString());
	}

	private LoaderManager.LoaderCallbacks<Cursor> mLoaderCallback = new LoaderManager.LoaderCallbacks<Cursor>() {
		private final String[] IMAGE_PROJECTION = {
				MediaStore.Images.Media.DATA,
				MediaStore.Images.Media.DISPLAY_NAME,
				MediaStore.Images.Media.DATE_ADDED,
				MediaStore.Images.Media._ID
		};

		@Override
		public Loader<Cursor> onCreateLoader(int id, Bundle data) {
			if (id == LOADER_ALL) {
				return new CursorLoader(PhotoSelectorActivity.this,
						MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
						IMAGE_PROJECTION,
						null,
						null,
						IMAGE_PROJECTION[2] + " DESC");
			} else if (id == LOADER_CATEGORY) {//用like会有问题，存在路径相包含的情况
				return new CursorLoader(PhotoSelectorActivity.this,
						MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
						IMAGE_PROJECTION,
						null,
						null,
						IMAGE_PROJECTION[2] + " DESC");
			}
			return null;
		}

		@Override
		public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
			if (data != null) {
				List<Image> images = new ArrayList<>();
				int count = data.getCount();
				if (count > 0) {
					data.moveToFirst();
					do {
						String path = data.getString(data.getColumnIndexOrThrow(IMAGE_PROJECTION[0]));
						String name = data.getString(data.getColumnIndexOrThrow(IMAGE_PROJECTION[1]));
						long dateTime = data.getLong(data.getColumnIndexOrThrow(IMAGE_PROJECTION[2]));

						File imageFile = new File(path);
						if (!imageFile.exists() || null == imageFile.getParentFile()) {
							continue;
						}
						if(imageFile.getParentFile().getAbsolutePath().contains("/Images/Cache/HouseImage/")){//FileUtils.DEFAULT_SAVE_IMAGE_PATH_UPLOAD
							continue;
						}
						Image image = new Image(path, name, dateTime, imageFile.length());
						if (!mHasFolder) {
							File folderFile = imageFile.getParentFile();
							Folder folder = new Folder();
							folder.name = folderFile.getName();
							folder.path = folderFile.getAbsolutePath();
							folder.cover = image;
							if (!mAlbumList.contains(folder)) {
								List<Image> imageList = new ArrayList<>();
								if (image.length > 0) {
									imageList.add(image);
									folder.images = imageList;
									mAlbumList.add(folder);
								}
							} else {
								// 更新
								Folder f = mAlbumList.get(mAlbumList.indexOf(folder));
								if (image.length > 0) {
									f.images.add(image);
								}
							}
						}
						if (image.length > 0) {
							images.add(image);
						}
					} while (data.moveToNext());
					if(TextUtils.isEmpty(mFolderPath)){
						mImageAdapter.setData(images);
					}else{
						Folder targetFolder = new Folder(mFolderPath);
						if(mAlbumList.contains(targetFolder)){
							mImageAdapter.setData(mAlbumList.get(mAlbumList.indexOf(targetFolder)).images);
						}else{
							mImageAdapter.setData(images);
						}
					}
					mImageAdapter.setDefaultSelected(mArguments.selectedImages);
					mFolderPopupAdapter.setData(mAlbumList);
					mHasFolder = true;
				}
			}
		}

		@Override
		public void onLoaderReset(Loader<Cursor> loader) {
		}
	};

	/**
	 * 选择相机
	 */
	private void showCameraAction() {
		if (hasCameraPermission(mPermissionRequestCodeCamera)) {
			mCurrentPhotoPath = openCamera(Constants.FILE_PROVIDER_AUTHORITY);
			// 忽略手势
			GlobalVariableConfig.setIgnoreGestureFlag(true);
			GlobalVariableConfig.setThirdPartyPageOpenedFlag(true);
		}
	}

	@Override
	protected void permissionsAllGrantedSuccess(int requestCode) {
		if (requestCode == mPermissionRequestCodeCamera){
			showCameraAction();
		}
	}

	/**
	 * 创建弹出的ListView
	 */
	private void createPopupFolderList(int width, int height) {
		if (mFolderPopup != null) return;

		mFolderPopup = new ListPopupWindow(this);
		mFolderPopup.setContentWidth(width);
		mFolderPopup.setHeight(height * 5 / 8);
		mFolderPopup.setModal(true);
		mFolderPopup.setAdapter(mFolderPopupAdapter);
		mFolderPopup.setAnchorView(mFooter);
		mFolderPopup.setOnItemClickListener(new AdapterView.OnItemClickListener() {
												@Override
												public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
													if (i == 0) {
														mFolderPath = "";
														getSupportLoaderManager().restartLoader(LOADER_ALL, null, mLoaderCallback);
														mAlbumNameTv.setText(R.string.folder_all);
														mImageAdapter.setShowCamera(true);
													} else {
														Folder folder = (Folder) adapterView.getAdapter().getItem(i);
														if (null != folder) {
															Bundle args = new Bundle();
															args.putString("path", folder.path);
															mFolderPath = folder.path;
															getSupportLoaderManager().restartLoader(LOADER_CATEGORY, args, mLoaderCallback);
															mAlbumNameTv.setText(folder.name);
														}
														mImageAdapter.setShowCamera(false);
													}
													mFolderPopupAdapter.setSelectIndex(i);
													mFolderPopup.dismiss();
													mGridView.smoothScrollToPosition(0);
												}
											}
		);
	}

	@SuppressLint("SetTextI18n")
	private void onClickPhotoItem(AdapterView<?> adapterView, int position, int mode) {
		// 正常操作
		Image image = (Image) adapterView.getAdapter().getItem(position);
		if (image.length == 0) {
			showToast(R.string.msg_no_picture);
			return;
		}
		mCompleteTv.setEnabled(true);
		boolean contains = mArguments.selectedImages.contains(image.path);
		if (contains) {//取消选择
			mArguments.selectedImages.remove(image.path);
			boolean selected = mArguments.selectedImages.size() != 0;
			onImageUnselected(image.path);

			if (mode == SELECT_MODE_SINGLE && !selected) {
				mImageAdapter.clearSelected();
			}
		} else {//选择
			if (mode == SELECT_MODE_SINGLE) {//如果是单选
				mArguments.selectedImages.clear();
			} else if (mArguments.remainCount == mArguments.selectedImages.size()) {//如果是多选
				showToast(String.format(getString(R.string.msg_amount_limit), mArguments.maxCount + ""));
				return;
			}
			mArguments.selectedImages.add(image.path);
			onImageSelected(image.path);
		}
		mSelectedCountTv.setText(String.valueOf(mArguments.selectedImages.size()));
		if (mode != SELECT_MODE_SINGLE || !contains) {
			mImageAdapter.select(image);
		}
	}
}